<?php

class Weixin {
	private $APPID = 'wx4c0a5bdb169cbebb';
	private $APPSECRET = 'b902209f70bf4b83eb1211ced2ecca51';
	private $PARTNERID = '1448200102';
    private $APIPAY = '8dec58132ac5a511494c472d8624636f';
    private $REDIRECT_URI = '';
	private $SCOPE = 'snsapi_userinfo';
	private $OPENID = '';
	private $ACCESS_TOKEN = '';
	
	public function __construct(){
		$this->REDIRECT_URI = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
		$openId = $this->getOpenId();
	}

	public function getOpenId(){
		$mp_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->APPID.'&redirect_uri='.$this->REDIRECT_URI.'&response_type=code&scope='.$this->SCOPE.'&state=STATE#wechat_redirect';
		if (empty($_GET['code'])) {
			header('Location: ' . $mp_url);
		}else{
			$d = json_decode(file_get_contents(sprintf(
            'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
            $this->APPID,
            $this->APPSECRET,
            $_GET['code']
        )), true);

        if (empty($d)) {
            throw new Exception(__METHOD__);
        }

        if (empty($d['errcode']) && isset($d['openid'])) {
            $this->OPENID =  $d['openid'];
            $this->ACCESS_TOKEN = $d['access_token'];
        }
        

        	//$t = json_decode(file_get_contents(sprintf('https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s',$this->APPID,$this->ACCESS_TOKEN)),true);
           // $this->ACCESS_TOKEN = $t['access_token'];

       // throw new Exception(var_export($d, true));
		}
	}
	
	public function getSNSUserInfo(){
		$info = json_decode(file_get_contents(sprintf('https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',$this->ACCESS_TOKEN,$this->OPENID)),true);
		//过滤可能出现的表情 by lijianjun 20170321
//		echo '666<br />';
		//$nickname=unicode2utf8($info['nickname']);
		$nickname=json_encode($info['nickname']);
		//echo htmlspecialchars($nickname).'<br/>';
		$info['nickname']=preg_replace("#(\\\ud[0-9a-f]{3})|(\\\ue[0-9a-f]{3})#ie","",$nickname);
		$info['nickname']=str_replace(" ","",$info['nickname']);
		$info['nickname']=json_decode($info['nickname']);
		//echo htmlspecialchars($info['nickname']);exit;
		//echo '777<br />';
		//var_dump($info);exit;
		return $info;
	}

	
}

?>